package com.tocean.demo.service;

import com.alibaba.fastjson.JSONObject;
import com.tocean.demo.dto.Result;
import com.tocean.demo.entity.Attr.Verification;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Service
public class WebService {

    /**
     * 向目的URL发送post请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  Result
     */
    public String sendPostRequest(String url, Map<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用Result类格式化
        ResponseEntity<Result> response = client.postForEntity(url, requestEntity, Result.class);
        return JSONObject.toJSONString(response.getBody().getData());
    }

    public String sendPostAnswer(String url, Map<String, List<Verification>> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, List<Verification>>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用Result类格式化
        ResponseEntity<Result> response = client.postForEntity(url, requestEntity, Result.class);
        return JSONObject.toJSONString(response.getBody().getData());
    }


    /**
     *
     * @param url
     * @param params
     * @return
     */
    public static String sendGetRequest(String url, MultiValueMap<String, String> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.GET;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用String 类格式化
        ResponseEntity<Result> response = client.exchange(url, method, requestEntity, Result.class);
        return JSONObject.toJSONString(response.getBody().getData());
    }


}
